import { fetchSevenStar } from './fetch'
import localForage from 'localforage'
import dayjs from 'dayjs'

const CACHE_DATA_KEY = 'getHistoryPageListV1_500_sevenStar'
// 最近一次开奖日期是否是今天
const lastTimeIsToday = dateString => dayjs(dateString).isSame(dayjs(), 'days')
// 最近一次开奖日期是否是昨天
const lastTimeIsYestoday = dateString => dayjs(dateString).isSame(dayjs().subtract(1, 'days'), 'days')
// 当前时间是否在21点之前
const nowIsBefore21h = _ => dayjs().hour() < 21

const getSevenStarData = (pageSize = 10, reFetch = false) => {
    return new Promise(async (resolve, reject) => {

        let isFromCache = false
        const cacheData = await localForage.getItem(CACHE_DATA_KEY);

        if (cacheData) {
            const lastTimeDate = cacheData.list[0].lotteryDrawTime
            if (lastTimeIsToday(lastTimeDate) || (lastTimeIsYestoday(lastTimeDate) && nowIsBefore21h())) {
                isFromCache = true
            }
        }

        if (reFetch) {
            // 传pageSize，不走缓存
            isFromCache = false
        }
       
        if (isFromCache) {
            resolve(cacheData)
        } else {
            const list = []
            const fetchList = Array(pageSize).fill(null).map((_, index) => fetchSevenStar(index + 1))
            const res = await Promise.all(fetchList)

            res.map(data => data.list.map(item => list.push(item)))

            await localForage.setItem(CACHE_DATA_KEY, { list })

            resolve({
                list
            })
        }
    })
}

export default getSevenStarData